/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.rpc.workflow.user.special;

import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.CompanyRpcService;
import com.je.rbac.rpc.workflow.util.WorkFlowParserUserUtil;
import com.je.rbac.service.IconType;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public abstract class AbstractSpecialUserParser {

    /**
     * 检查用户在不在，已选择人员中
     */
    public abstract Boolean checkUser(DynaBean dynaBean,String userId);
    /**
     * 获取特殊处理后，最终的人员 唯一信息 账号部门id （最终人员包不包括自己、当前登录人）
     */
    public abstract List<DynaBean> getUserInfo(String userId,Boolean addOwn);

    /**
     * 查询唯一信息，账号部门视图 JE_RBAC_VACCOUNTDEPT
     *
     * @param countUserId
     * @return
     */
    public DynaBean findVacCountDeptUserById(String countUserId) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        DynaBean countDept = metaService.selectOne("JE_RBAC_VACCOUNTDEPT",
                ConditionsWrapper.builder().eq("JE_RBAC_ACCOUNTDEPT_ID", countUserId).eq("SY_STATUS", "1"));
        return countDept;
    }
    /**
     * 通过账号查找真实的部门用户信息
     *
     * @param userId 用户id
     * @param deptId 部门id
     * @return1
     */
    public DynaBean findDeptUserByUserIdAndDeptId(String userId, String deptId) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        //查询部门账号关联表，找到真实的用户id和部门id
        DynaBean dynaBean = metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder().
                eq("JE_RBAC_DEPARTMENT_ID", deptId).eq("JE_RBAC_USER_ID", userId));
        return dynaBean;
    }

    public DynaBean findDeptUserByDeptUserId(String deptUserId) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        DynaBean dynaBean = metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder().
                eq("JE_RBAC_DEPTUSER_ID", deptUserId));
        return dynaBean;
    }

    public List<DynaBean> findUserByUserId(String userId) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        List<DynaBean> dynaBeans = metaService.select("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder().
                eq("JE_RBAC_USER_ID", userId));
        return dynaBeans;
    }

    public DynaBean findVacCountDeptUserByUserIdAndDpeId(String userId, String deptId) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        DynaBean countDept = metaService.selectOne("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder()
                .eq("ACCOUNTDEPT_DEPT_ID", deptId).eq("USER_ASSOCIATION_ID", userId));
        return countDept;
    }

    public List<DynaBean> findAccountDeptByUserIdAndDpeId(String strSql) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        List<DynaBean> countDept = metaService.selectBeanSql("JE_RBAC_VACCOUNTDEPT"," where 1=1 "+strSql);
        return countDept;
    }

    /**
     * 构建树形节点
     *
     * @param template     模板
     * @param parentNodeId 父节点ID
     * @param bean         当前bean
     * @return
     */
    public JSONTreeNode buildTreeNode(JSONTreeNode template, String parentNodeId, DynaBean bean) {
        JSONTreeNode node = new JSONTreeNode();
        node.setId(bean.getPkValue());
        node.setParent(parentNodeId);
        node.setLeaf(true);
        if (StringUtil.isNotEmpty(template.getText())) {
            node.setText(bean.getStr(template.getText()));
        }
        if (StringUtil.isNotEmpty(template.getCode())) {
            node.setCode(bean.getStr(template.getCode()));
        }
        //节点信息
        if (StringUtil.isNotEmpty(template.getNodeInfo())) {
            node.setNodeInfo(bean.getStr(template.getNodeInfo()));
        }
        //节点信息类型
        if (StringUtil.isNotEmpty(template.getNodeInfoType())) {
            node.setNodeInfoType(bean.getStr(template.getNodeInfoType()));
        }
        //节点类型
        if (StringUtil.isNotEmpty(template.getNodeType())) {
            node.setNodeType(bean.getStr(template.getNodeType()));
        }
        //节点路径
        if (StringUtil.isNotEmpty(template.getNodePath())) {
            node.setNodePath(bean.getStr(template.getNodePath()));
        }
        //是否禁用
        if (StringUtil.isNotEmpty(template.getDisabled())) {
            node.setDisabled(bean.getStr(template.getDisabled()));
        }
        //树形排序
        if (StringUtil.isNotEmpty(template.getTreeOrderIndex())) {
            node.setTreeOrderIndex(bean.getStr(template.getTreeOrderIndex()));
        }
        //节点类型
        if (StringUtil.isNotEmpty(template.getNodeType())) {
            node.setNodeType(bean.getStr(template.getNodeType()));
        }
        //图标样式
        if (StringUtil.isNotEmpty(template.getIcon())) {
            node.setIcon(bean.getStr(template.getIcon()));
        }
        //是否禁用
        if (StringUtil.isNotEmpty(template.getDisabled())) {
            node.setDisabled(bean.getStr(template.getDisabled()));
        } else {
            node.setDisabled("0");
        }
        //描述
        if (StringUtil.isNotEmpty(template.getDescription())) {
            node.setDescription(bean.getStr(template.getDescription()));
        }
        //排序
        if (StringUtil.isNotEmpty(template.getOrderIndex())) {
            node.setOrderIndex(bean.getStr(template.getOrderIndex()) + "");
        }
        node.setBean(bean.getValues());
        return node;
    }

    /***
     * 构建部门树
     * @param template
     * @param rootNode
     * @param deptBeanList
     */
    public void buildDeptUserTree(JSONTreeNode template, JSONTreeNode rootNode, List<DynaBean> deptBeanList) {
        for (DynaBean deptBean : deptBeanList) {
            deptBean.put("DEPARTMENT_ICON", IconType.TCONTYPE_DEPART.getVal());
            if (!rootNode.getId().equals(deptBean.getStr("SY_PARENT"))) {
                continue;
            }
            JSONTreeNode deptBeanNode = buildTreeNode(template, rootNode.getId(), deptBean);
            rootNode.getChildren().add(deptBeanNode);
        }
        if (rootNode.getChildren() == null || rootNode.getChildren().isEmpty()) {
            return;
        }
        for (JSONTreeNode eachChildNode : rootNode.getChildren()) {
            buildDeptUserTree(template, eachChildNode, deptBeanList);
        }
    }

    /***
     * 构建部门用户
     * @param rootNode
     * @param departmentUserBeanList
     */
    public void recursiveDepartmentUserTreeNode(JSONTreeNode rootNode, List<DynaBean> departmentUserBeanList, Boolean multiple) {
        if ("department".equals(rootNode.getNodeInfoType())) {
            for (DynaBean eachDepartmentUserBean : departmentUserBeanList) {
                eachDepartmentUserBean.put("DEPARTMENT_ICON", IconType.TCONTYPE_ROLE.getVal());
                if (!rootNode.getId().equals(eachDepartmentUserBean.getStr("ACCOUNTDEPT_DEPT_ID"))) {
                    continue;
                }
                WorkFlowParserUserUtil.parseAccountDepartmentToTree(rootNode, eachDepartmentUserBean, multiple, true);
            }
        }
        if (rootNode.getChildren() == null || rootNode.getChildren().isEmpty()) {
            return;
        }
        for (JSONTreeNode eachChildNode : rootNode.getChildren()) {
            recursiveDepartmentUserTreeNode(eachChildNode, departmentUserBeanList, multiple);
        }
    }

    /***
     * 构建公司-用户树
     * @param companyBeanList
     * @param userBeanList
     * @return
     */
    public JSONTreeNode buildCompanyUserTree(List<DynaBean> companyBeanList, List<DynaBean> userBeanList, Boolean multiple) {
        CompanyRpcService companyRpcService = SpringContextHolder.getBean(CompanyRpcService.class);
        Set<String> companyIds = new HashSet<>();
        for (DynaBean eachCompanyBean : companyBeanList) {
            companyIds.add(eachCompanyBean.get("JE_RBAC_COMPANY_ID").toString());
        }
        JSONTreeNode companyRootNode = companyRpcService.buildCompanyTree(String.join(",", companyIds));
        for (JSONTreeNode companyNode : companyRootNode.getChildren()) {
            if (null == userBeanList) {
                break;
            }
            for (DynaBean eachBean : userBeanList) {
                if (!companyNode.getBean().get("JE_RBAC_COMPANY_ID").equals(eachBean.get("SY_COMPANY_ID"))) {
                    continue;
                }
                WorkFlowParserUserUtil.parseAccountDepartmentToTree(companyNode, eachBean, multiple, true);
            }
        }
        return companyRootNode;
    }

}
